package com.flca.frw.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShellUtils {
	private static Logger logger = LoggerFactory.getLogger(ShellUtils.class);

	public static ScriptResult execShellScript(String aCommand) throws IOException {
		return execShellScript(aCommand, null);
	}

	public static ScriptResult execShellScript(String aCommand, String aArgs[]) throws IOException {
		List<String> cmd = new ArrayList<String>();
		cmd.add(aCommand);

		if (aArgs != null) {
			for (String arg : aArgs) {
				cmd.add(arg);
			}
		}

		logger.info("start executing : " + cmd);

		ProcessBuilder builder = new ProcessBuilder(cmd);
//		System.out.println("Directory : " + System.getenv("temp"));
		final Process process = builder.start();
		try {
			process.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		StringBuffer sb = execScriptReadResult(process);
		logger.info("finished " + cmd);
		return new ScriptResult(process.exitValue(), sb.toString());
	}

	private static StringBuffer execScriptReadResult(final Process process) throws IOException {
//		System.out.println("exitvalue = " + process.exitValue());
		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		StringBuffer sb = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line + "\n");
		}
		return sb;
	}

	/**
	 * return true is all searchString(s) can be found in a running process
	 * Something similar to (ps -ef | grep x1 | grep x2)
	 * 
	 * @param searchStrings
	 * @return
	 */
	public static boolean isProcessRunning(String[] searchStrings) {
		return false;// TODO
	}

	public static String getOs() {
		return System.getProperty("os.name");
	}

	public static boolean isWindows() {
		return getOs().toLowerCase().startsWith("win");
	}

	public static boolean isLinux() {
		return getOs().toLowerCase().startsWith("linux");
	}

	public static String getUserDir() {
		return System.getProperty("user.dir");
	}

	public static String getSeperator() {
		return System.getProperty("file.separator");
	}

	public static String getClassPathDelim() {
		return (ShellUtils.isWindows()) ? ";" : ":";
	}
	
	public static String getTempDir() {
		String result = System.getProperty("java.io.tmpdir");
		
		if (result != null) {
			return FileUtils.appendSeperator(result);
		} else {
			return (ShellUtils.isWindows()) ? "c:\\temp\\" : "/tmp/";
		}
	}

	public static String getCurrentDir() {
		try {
			String result = new File(".").getCanonicalPath();
			return FileUtils.appendSeperator(result);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static class ScriptResult {
		private boolean okay;
		private String returnMessage;
		
		public ScriptResult(int exitValue, String returnMessage) {
			super();
			this.okay = (exitValue == 0);
			this.returnMessage = returnMessage;
		}

		public boolean isOkay() {
			return okay;
		}

		public String getReturnMessage() {
			return returnMessage;
		}
	}
}
